# -*- coding: utf-8 -*-
"""
自定义管道组件
"""

import os
import ppc
import ppc.pipe


class ReplaceFilter(ppc.pipe.Pipe):
    """文件内容替换"""

    def handle(self):
        fr = self['from'].value
        to = self['to'].value
        ec = self['encoding'].value

        path = self.input['path']
        content = None
        try:
            with open(path, mode = 'r', encoding = ec) as f:
                content = f.read()
                if content.find(fr):
                    content = content.replace(fr, to)
                    end = content.find("</html>")
                    if end > -1:
                        content = content[:end + 7]
                else:
                    content = None
                f.close()
        except Exception as ex:
            print("ERROR:{0} cannot replace!\n".format(self.input['path']));

        if content:
            with open(path, mode = 'w') as f:
                f.write(content)
                f.close
            self.transfer(self.input)
